package com.dingwen.treasure.tkmybatis.convert;

import com.dingwen.treasure.base.enums.BaseEnum;
import com.dingwen.treasure.base.util.ReflectUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * AbstractEnumHandler
 * 　@author dingwen
 * 　@date 2022/6/15
 */
public abstract class AbstractEnumHandler<E extends BaseEnum> implements TypeHandler<E> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, E e, JdbcType jdbcType) throws SQLException {
        preparedStatement.setObject(i, e.getCode());
    }

    @Override
    public E getResult(ResultSet resultSet, String s) throws SQLException {
        String code = resultSet.getString(s);
        return resultSet.wasNull() ? null : parse(code);
    }

    @Override
    public E getResult(ResultSet resultSet, int i) throws SQLException {
        String code = resultSet.getString(i);
        return resultSet.wasNull() ? null : parse(code);
    }

    @Override
    public E getResult(CallableStatement callableStatement, int i) throws SQLException {
        String code = callableStatement.getString(i);
        return callableStatement.wasNull() ? null : parse(code);
    }


    /**
     * 枚举转换
     *
     * @param code
     * @return
     */
    E parse(String code) {
        Class<E> clazz = ReflectUtil.getClassForGeneric(0, this);
        for (E e : clazz.getEnumConstants()) {
            if (e.getCode().toString().equals(code)) {
                return e;
            }
        }
        return null;
    }
}
